<?php
/**
 * DESC:
 * 作者:晨光
 * EMAIL:461718846@qq.com
 * DATE:2020/5/16
 */

namespace app\common\model;


use think\Model;

class Goods extends Model
{
    /**
     * 分类表
     */
    public function cate(){
        return $this->belongsToMany('goodsCate','GoodsCateRelated');
    }
    /**
     * 关联分类表
     */
    public function cateRelated(){
        return $this->hasMany('GoodsCateRelated');
    }

    public function goodsFormat(){
        return $this->hasMany('GoodsFormat');
    }

    public function shop(){
        return $this->belongsTo('shop')->bind([
            'shop_name'=>'name','shop_phone'=>'phone'
        ]);
    }

    /**
     * 获取商品单价，默认是规格中价格最低的那个
     * @param $value
     * @param $data
     */
    public function getPriceAttr($value,$data){
        return GoodsFormat::where('goods_id','=',$data['id'])->where('price','>',0)->order('price asc')->value('price');
    }

    /**
     * 商品原价,默认是规格中价格最高的那个
     * @param $value
     * @param $data
     * @return mixed
     */
    public function getOriginalPriceAttr($value,$data){
        return GoodsFormat::where('goods_id','=',$data['id'])->order('original_price desc')->value('original_price');
    }

    /**
     * 获取当前商品的库存,默认最少的那个
     * @param $value
     * @param $data
     * @return mixed
     */
    public function getStockAttr($value,$data){
        return GoodsFormat::where('goods_id','=',$data['id'])->order('stock asc')->value('stock');
    }

    /**
     * 编辑商品
     * @param $param
     * @return bool
     */
    public static function goods_edit_save($param){
        $goodsModel = new \app\common\model\Goods();
        $res = $goodsModel->allowField(true)->isUpdate(true)->save($param,['id'=>$param['id']]);
        if ($res !== false){
            saveAdminLog("编辑商品内容");
            return true;
        }else{
            return false;
        }
    }
}
